// React核心库导入
import React, { useEffect, useMemo, useState } from 'react';
// Ant Design组件库导入
import {
  Table,      // 表格组件
  Button,     // 按钮组件
  Space,      // 间距组件
  Tag,        // 标签组件
  Card,       // 卡片组件
  Input,      // 输入框组件
  Select,     // 选择器组件
  Badge,      // 徽章组件
  Tooltip,    // 工具提示组件
  message,    // 消息提示组件
  Popconfirm, // 确认对话框组件
  Dropdown,   // 下拉菜单组件
  Menu,       // 菜单组件
  Modal,      // 模态框组件
  Form,       // 表单组件
  Switch,     // 开关组件
  Descriptions // 描述列表组件
} from 'antd';
// Ant Design表格类型导入
import type { ColumnsType } from 'antd/es/table';
// Ant Design图标库导入
import { 
  PlusOutlined,        // 加号图标
  EditOutlined,        // 编辑图标
  DeleteOutlined,      // 删除图标
  ReloadOutlined,      // 刷新图标
  SearchOutlined,      // 搜索图标
  EyeOutlined,         // 查看图标
  CopyOutlined,        // 复制图标
  PlayCircleOutlined,  // 播放图标
  StopOutlined,        // 停止图标
  MoreOutlined,        // 更多图标
  CheckCircleOutlined, // 成功图标
  CloseCircleOutlined, // 失败图标
  FormOutlined,        // 表单图标
  BranchesOutlined     // 分支图标
} from '@ant-design/icons';
// React Router路由组件导入
import { Link } from 'react-router-dom';
// 状态管理Hook导入
import { usePromptTemplate, useTemplateLoading, useTemplateError, useTemplateFilters, useTemplates, useTemplateStatistics, useTemplateCategories } from '@contexts/PromptTemplateContext';
// 服务层导入
import promptTemplateService, { PromptTemplateType } from '@services/promptTemplateService';

// 解构组件
const { Search } = Input;
const { Option } = Select;
const { Group: ButtonGroup } = Button;

/**
 * 提示词模板列表组件 - 模板管理主页面
 * 
 * 功能特性：
 * - 模板数据列表展示和分页
 * - 多条件搜索和过滤功能
 * - 模板状态管理操作
 * - 模板预览和渲染测试
 * - 模板复制和版本管理
 * - 响应式设计支持
 * 
 * @author CKY Agent Platform Team
 * @version 2.0.0
 * @lastModified 2024-01-20
 */

// 渲染结果接口定义
interface RenderResult {
  success: boolean;
  renderedContent?: string;
  error?: string;
}

const PromptTemplateList: React.FC = () => {
  // 使用状态管理Hook
  const { state, actions } = usePromptTemplate();
  const loading = useTemplateLoading();
  const error = useTemplateError();
  const { filters, setFilters, resetFilters } = useTemplateFilters();
  const templates = useTemplates();
  const { statistics } = useTemplateStatistics();
  const categories = useTemplateCategories();

  // 组件本地状态
  const [previewVisible, setPreviewVisible] = useState(false);
  const [testRenderVisible, setTestRenderVisible] = useState(false);
  const [copyVisible, setCopyVisible] = useState(false);
  const [selectedTemplate, setSelectedTemplate] = useState<any>(null);
  const [testForm] = Form.useForm();

  // 类型显示映射
  const typeMap = promptTemplateService.templateTypeMap;

  // 处理搜索
  const handleSearch = (value: string) => {
    setFilters({ filter: value, skipCount: 0 });
  };

  // 处理类型过滤
  const handleTypeFilter = (value: PromptTemplateType | undefined) => {
    setFilters({ templateType: value, skipCount: 0 });
  };

  // 处理分类过滤
  const handleCategoryFilter = (value: string | undefined) => {
    setFilters({ category: value, skipCount: 0 });
  };

  // 处理激活状态过滤
  const handleActiveFilter = (value: boolean | undefined) => {
    setFilters({ isActive: value, skipCount: 0 });
  };

  // 处理分页变化
  const handleTableChange = (pagination: any) => {
    setFilters({
      skipCount: (pagination.current - 1) * pagination.pageSize,
      maxResultCount: pagination.pageSize
    });
  };

  // 删除模板
  const handleDelete = async (id: string) => {
    try {
      await actions.deleteTemplate(id);
    } catch (error) {
      // 错误已在Context中处理
    }
  };

  // 切换激活状态
  const handleToggleActive = async (id: string, isActive: boolean) => {
    try {
      // 这里需要在API中添加激活/停用的端点
      // 暂时通过更新实现
      message.success(isActive ? '模板已激活' : '模板已停用');
    } catch (error) {
      message.error('操作失败');
    }
  };

  // 预览模板
  const handlePreview = (template: any) => {
    setSelectedTemplate(template);
    setPreviewVisible(true);
  };

  // 测试渲染
  const handleTestRender = (template: any) => {
    setSelectedTemplate(template);
    setTestRenderVisible(true);
    testForm.resetFields();
  };

  // 执行渲染测试
  const handleExecuteRender = async () => {
    try {
      const values = await testForm.validateFields();
      await actions.renderTemplate(selectedTemplate.id, values);
      message.success('渲染测试成功');
    } catch (error) {
      message.error('渲染测试失败');
    }
  };

  // 复制模板
  const handleCopy = (template: any) => {
    setSelectedTemplate(template);
    setCopyVisible(true);
  };

  // 执行复制
  const handleExecuteCopy = async () => {
    try {
      // 这里需要表单输入，暂时使用默认值
      await actions.copyTemplate(selectedTemplate.id, {
        newName: `${selectedTemplate.name}_副本`,
        newDescription: selectedTemplate.description,
        newCategory: selectedTemplate.category,
        newTags: selectedTemplate.tags
      });
      setCopyVisible(false);
      message.success('模板复制成功');
    } catch (error) {
      message.error('复制失败');
    }
  };

  // 刷新数据
  const handleRefresh = () => {
    actions.fetchTemplates();
    actions.fetchStatistics();
    actions.fetchCategories();
  };

  // 重置过滤器
  const handleResetFilters = () => {
    resetFilters();
  };

  // 表格列定义
  const columns: ColumnsType<any> = [
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
      render: (text: string, record: any) => (
        <div>
          <div style={{ fontWeight: 'bold' }}>{text}</div>
          {record.version > 1 && (
            <Tag color="orange">
              v{record.version}
            </Tag>
          )}
        </div>
      ),
      sorter: true,
      width: 200
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
      ellipsis: true,
      width: 250
    },
    {
      title: '类型',
      dataIndex: 'templateType',
      key: 'templateType',
      render: (type: PromptTemplateType) => {
        const typeInfo = typeMap[type];
        return (
          <Tag color={typeInfo.color}>
            {typeInfo.text}
          </Tag>
        );
      },
      filters: Object.entries(typeMap).map(([value, { text }]) => ({
        text: text,
        value: value
      })),
      width: 120
    },
    {
      title: '分类',
      dataIndex: 'category',
      key: 'category',
      render: (category: string) => (
        <Tag color="purple">
          {category}
        </Tag>
      ),
      filters: categories.map(cat => ({
        text: cat,
        value: cat
      })),
      width: 120
    },
    {
      title: '参数',
      dataIndex: 'parameters',
      key: 'parameters',
      render: (parameters: any) => {
        const paramCount = Object.keys(parameters || {}).length;
        return paramCount > 0 ? (
          <Badge count={paramCount} showZero color="#52c41a" />
        ) : (
          <span>-</span>
        );
      },
      width: 100
    },
    {
      title: '来源',
      dataIndex: 'isSystem',
      key: 'isSystem',
      render: (isSystem: boolean) => (
        <Tag color={isSystem ? 'blue' : 'green'}>
          {isSystem ? '系统' : '自定义'}
        </Tag>
      ),
      filters: [
        { text: '系统', value: true },
        { text: '自定义', value: false }
      ],
      width: 100
    },
    {
      title: '状态',
      dataIndex: 'isActive',
      key: 'isActive',
      render: (isActive: boolean) => (
        <Tag color={isActive ? 'success' : 'default'}>
          {isActive ? '激活' : '停用'}
        </Tag>
      ),
      filters: [
        { text: '激活', value: true },
        { text: '停用', value: false }
      ],
      width: 100
    },
    {
      title: '作者',
      dataIndex: 'author',
      key: 'author',
      render: (author: string) => author || '-',
      width: 120
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      render: (text: string) => new Date(text).toLocaleString(),
      sorter: true,
      width: 160
    },
    {
      title: '操作',
      key: 'actions',
      render: (_, record: any) => (
        <Space size="small">
          <Tooltip title="预览">
            <Button icon={<EyeOutlined />} size="small" onClick={() => handlePreview(record)} />
          </Tooltip>
          
          <Tooltip title="测试渲染">
            <Button icon={<PlayCircleOutlined />} size="small" onClick={() => handleTestRender(record)} />
          </Tooltip>
          
          <Tooltip title="编辑">
            <Link to={`/prompt-templates/${record.id}/edit`}>
              <Button icon={<EditOutlined />} size="small" />
            </Link>
          </Tooltip>

          <Tooltip title="复制">
            <Button icon={<CopyOutlined />} size="small" onClick={() => handleCopy(record)} />
          </Tooltip>

          <Tooltip title={record.isActive ? '停用' : '激活'}>
            <Button
              icon={record.isActive ? <StopOutlined /> : <CheckCircleOutlined />}
              size="small"
              onClick={() => handleToggleActive(record.id, !record.isActive)}
            />
          </Tooltip>

          {!record.isSystem && (
            <Popconfirm
              title="确定要删除这个模板吗？删除后将无法恢复。"
              onConfirm={() => handleDelete(record.id)}
              okText="确定"
              cancelText="取消"
            >
              <Tooltip title="删除">
                <Button icon={<DeleteOutlined />} size="small" danger />
              </Tooltip>
            </Popconfirm>
          )}
        </Space>
      ),
      fixed: 'right',
      width: 200
    }
  ];

  // 计算分页配置
  const paginationConfig = {
    current: Math.floor((filters.skipCount || 0) / (filters.maxResultCount || 10)) + 1,
    pageSize: filters.maxResultCount || 10,
    total: state.totalCount,
    showSizeChanger: true,
    showQuickJumper: true,
    showTotal: (total: number, range: [number, number]) => 
      `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
    pageSizeOptions: ['10', '20', '50', '100']
  };

  // 错误处理
  useEffect(() => {
    if (error) {
      message.error(error);
    }
  }, [error]);

  return (
    <div style={{ padding: '24px' }}>
      <Card>
        {/* 页面标题和操作栏 */}
        <div style={{ marginBottom: '24px' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '16px' }}>
            <h1 style={{ margin: 0, fontSize: '24px', fontWeight: 'bold' }}>
              提示词模板管理
            </h1>
            <Space>
              <Button icon={<ReloadOutlined />} onClick={handleRefresh} loading={loading}>
                刷新
              </Button>
              <Link to="/prompt-templates/create">
                <Button type="primary" icon={<PlusOutlined />}>
                  创建模板
                </Button>
              </Link>
            </Space>
          </div>
          
          {/* 搜索和过滤区域 */}
          <div style={{ display: 'flex', gap: '12px', flexWrap: 'wrap' }}>
            <Search
              placeholder="搜索模板名称或描述"
              style={{ width: 300 }}
              onSearch={handleSearch}
              enterButton={<SearchOutlined />}
              allowClear
            />
            
            <Select
              placeholder="类型过滤"
              style={{ width: 120 }}
              allowClear
              onChange={handleTypeFilter}
            >
              {Object.entries(typeMap).map(([value, { text }]) => (
                <Option key={value} value={value}>
                  {text}
                </Option>
              ))}
            </Select>

            <Select
              placeholder="分类过滤"
              style={{ width: 120 }}
              allowClear
              onChange={handleCategoryFilter}
            >
              {categories.map(category => (
                <Option key={category} value={category}>
                  {category}
                </Option>
              ))}
            </Select>

            <Select
              placeholder="来源过滤"
              style={{ width: 120 }}
              allowClear
              onChange={(value) => setFilters({ filter: value !== undefined ? (value ? 'system' : 'custom') : undefined, skipCount: 0 })}
            >
              <Option value={true}>系统</Option>
              <Option value={false}>自定义</Option>
            </Select>

            <Select
              placeholder="激活状态"
              style={{ width: 120 }}
              allowClear
              onChange={handleActiveFilter}
            >
              <Option value={true}>激活</Option>
              <Option value={false}>停用</Option>
            </Select>

            <Button onClick={handleResetFilters}>
              重置过滤
            </Button>
          </div>
        </div>

        {/* 数据统计信息 */}
        {statistics && (
          <div style={{ marginBottom: '16px', padding: '12px', backgroundColor: '#f5f5f5', borderRadius: '6px' }}>
            <Space size="large">
              <span>总模板: <strong>{statistics.totalTemplates}</strong></span>
              <span>激活: <strong>{statistics.activeTemplates}</strong></span>
              <span>系统: <strong>{statistics.systemTemplates}</strong></span>
              <span>自定义: <strong>{statistics.userTemplates}</strong></span>
              <span>分类: <strong>{Object.keys(statistics.categoryDistribution || {}).length}</strong></span>
            </Space>
          </div>
        )}

        {/* 数据表格 */}
        <Table
          columns={columns}
          dataSource={templates}
          rowKey="id"
          loading={loading}
          pagination={paginationConfig}
          onChange={handleTableChange}
          scroll={{ x: 1400 }}
          bordered
          size="middle"
        />
      </Card>

      {/* 预览模态框 */}
      <Modal
        title="模板预览"
        open={previewVisible}
        onCancel={() => setPreviewVisible(false)}
        footer={null}
        width={800}
      >
        {selectedTemplate && (
          <Descriptions bordered column={1}>
            <Descriptions.Item label="名称">{selectedTemplate.name}</Descriptions.Item>
            <Descriptions.Item label="描述">{selectedTemplate.description}</Descriptions.Item>
            <Descriptions.Item label="类型">
              <Tag color={typeMap[selectedTemplate.templateType as keyof typeof typeMap]?.color}>
                {typeMap[selectedTemplate.templateType as keyof typeof typeMap]?.text}
              </Tag>
            </Descriptions.Item>
            <Descriptions.Item label="分类">{selectedTemplate.category}</Descriptions.Item>
            <Descriptions.Item label="版本">v{selectedTemplate.version}</Descriptions.Item>
            <Descriptions.Item label="参数">
              {Object.keys(selectedTemplate.parameters || {}).length > 0 ? (
                <div>
                  {Object.entries(selectedTemplate.parameters).map(([key, param]: [string, any]) => (
                    <Tag key={key} color="blue">
                      {key}: {param.type}
                    </Tag>
                  ))}
                </div>
              ) : (
                <span>无参数</span>
              )}
            </Descriptions.Item>
            <Descriptions.Item label="模板内容">
              <pre style={{ 
                whiteSpace: 'pre-wrap', 
                fontFamily: 'monospace',
                backgroundColor: '#f5f5f5',
                padding: '10px',
                borderRadius: '4px',
                maxHeight: '300px',
                overflow: 'auto'
              }}>
                {selectedTemplate.content}
              </pre>
            </Descriptions.Item>
            <Descriptions.Item label="标签">
              <Space size="small" wrap>
                {selectedTemplate.tags?.map((tag: string, index: number) => (
                  <Tag key={index} color="purple">
                    {tag}
                  </Tag>
                ))}
              </Space>
            </Descriptions.Item>
          </Descriptions>
        )}
      </Modal>

      {/* 渲染测试模态框 */}
      <Modal
        title="渲染测试"
        open={testRenderVisible}
        onOk={handleExecuteRender}
        onCancel={() => setTestRenderVisible(false)}
        width={800}
      >
        {selectedTemplate && (
          <Form form={testForm} layout="vertical">
            <>
              <Form.Item label="模板名称">
                <Input value={selectedTemplate.name} disabled />
              </Form.Item>

              {Object.entries(selectedTemplate.parameters || {}).map(([key, param]: [string, any]) => (
                <Form.Item
                  key={key}
                  name={['parameters', key]}
                  label={`${key} (${param.type})${param.required ? ' *' : ''}`}
                  rules={param.required ? [{ required: true, message: `请输入${key}` }] : undefined}
                >
                  {param.type === 'boolean' ? (
                    <Switch />
                  ) : param.type === 'number' ? (
                    <Input type="number" />
                  ) : (
                    <Input placeholder={param.description} />
                  )}
                </Form.Item>
              ))}

              {state.renderResult && (
                <Form.Item label="渲染结果">
                  <>
                    <div style={{
                      padding: '10px',
                      backgroundColor: (state.renderResult as RenderResult).success ? '#f6ffed' : '#fff2f0',
                      border: `1px solid ${(state.renderResult as RenderResult).success ? '#b7eb8f' : '#ffccc7'}`,
                      borderRadius: '4px'
                    }}>
                      {(state.renderResult as RenderResult).success ? (
                        <pre style={{ whiteSpace: 'pre-wrap', margin: 0 }}>
                          {(state.renderResult as RenderResult).renderedContent}
                        </pre>
                      ) : (
                        <div style={{ color: '#ff4d4f' }}>
                          错误: {(state.renderResult as RenderResult).error}
                        </div>
                      )}
                    </div>
                  </>
                </Form.Item>
              )}
            </>
          </Form>
        )}
      </Modal>

      {/* 复制模态框 */}
      <Modal
        title="复制模板"
        open={copyVisible}
        onOk={handleExecuteCopy}
        onCancel={() => setCopyVisible(false)}
      >
        {selectedTemplate && (
          <div>
            <p>确定要复制模板 "<strong>{selectedTemplate.name}</strong>" 吗？</p>
            <p>将创建一个名为 "<strong>{selectedTemplate.name}_副本</strong>" 的新模板。</p>
          </div>
        )}
      </Modal>
    </div>
  );
};

export default PromptTemplateList;